using Microsoft.Extensions.Logging;

namespace SeataNet.Core.Serialization
{
    /// <summary>
    /// 序列化器工厂接口
    /// </summary>
    public interface ISerializerFactory
    {
        /// <summary>
        /// 获取序列化器
        /// </summary>
        ISerializer GetSerializer(SerializerType type);

        /// <summary>
        /// 获取默认序列化器
        /// </summary>
        ISerializer GetDefaultSerializer();
    }

    /// <summary>
    /// 序列化器工厂默认实现
    /// </summary>
    public class DefaultSerializerFactory : ISerializerFactory
    {
        private readonly ILogger<DefaultSerializerFactory> _logger;
        private readonly ILoggerFactory _loggerFactory;
        private readonly Dictionary<SerializerType, ISerializer> _serializers;
        private readonly SerializerType _defaultType;

        public DefaultSerializerFactory(
            ILogger<DefaultSerializerFactory> logger,
            ILoggerFactory loggerFactory,
            SerializerType defaultType = SerializerType.Json)
        {
            _logger = logger;
            _loggerFactory = loggerFactory;
            _defaultType = defaultType;
            _serializers = new Dictionary<SerializerType, ISerializer>();

            InitializeSerializers();
        }

        private void InitializeSerializers()
        {
            // 注册JSON序列化器（默认必备）
            _serializers[SerializerType.Json] = new JsonSerializer(_loggerFactory.CreateLogger<JsonSerializer>());

            // 尝试注册Protobuf序列化器
            try
            {
                _serializers[SerializerType.Protobuf] = new ProtobufSerializer(_loggerFactory.CreateLogger<ProtobufSerializer>());
                _logger.LogInformation("Protobuf序列化器已注册");
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Protobuf序列化器注册失败，可能缺少protobuf-net依赖");
            }

            // 尝试注册MessagePack序列化器
            try
            {
                _serializers[SerializerType.MessagePack] = new MessagePackSerializer(_loggerFactory.CreateLogger<MessagePackSerializer>());
                _logger.LogInformation("MessagePack序列化器已注册");
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "MessagePack序列化器注册失败，可能缺少MessagePack依赖");
            }
        }

        public ISerializer GetSerializer(SerializerType type)
        {
            if (_serializers.TryGetValue(type, out var serializer))
            {
                return serializer;
            }

            _logger.LogWarning($"序列化器类型 {type} 不可用，使用JSON序列化器");
            return _serializers[SerializerType.Json];
        }

        public ISerializer GetDefaultSerializer()
        {
            return GetSerializer(_defaultType);
        }
    }
}
